﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using DevExpress.XtraEditors;
using DevExpress.XtraLayout;
using DevExpress.XtraLayout.Utils;
using HAF.FoundationLib;
using WareDealer;
using WareDealer.Mode;

namespace KillPrice
{
    public partial class UiProcess : DevExpress.XtraEditors.XtraUserControl
    {
        public UiProcess()
        {
            InitializeComponent();
        }

        private readonly List<ProductInfo> _wares = null;
        public UiProcess(List<ProductInfo> wareInfos)
        {
            _wares = wareInfos;
            InitializeComponent();
        }

        private int stepMain = 0;

        private void UiProcess_Load(object sender, EventArgs e)
        {
            SysParams.GatherMaxCount = 4;
            SysParams.GatherSplitCount = 1000;
            layoutMain.AllowCustomizationMenu = false;
            layProcessBar.AllowCustomizationMenu = false;
            InitProcess();
        }

        readonly Dictionary<string,ProgressBarControl> _subProgressBarDic = new Dictionary<string,ProgressBarControl>();
        /// <summary>
        /// 初始化进度条
        /// </summary>
        private void InitProcess()
        {
            stepMain = 0;
            if (_wares != null && _wares.Count >= SysParams.GatherSplitCount)
            {
                if (SysParams.AllowGetPrice)
                {
                    for (int i = 1; i <= SysParams.GatherMaxCount; i++)
                    {
                        ProgressBarControl runBarControl = new ProgressBarControl()
                        {
                            Name = "SubGatherPrice" + i,
                            Visible = true
                        };

                        LayoutControlItem tmpItem = new LayoutControlItem(layProcessBar, runBarControl)
                        {
                            Text = string.Format("价格采集{0}", i),
                            TextVisible = true,
                            Visibility = LayoutVisibility.Always
                        };

                        _subProgressBarDic.Add(Guid.NewGuid().ToString(), runBarControl);
                    }
                }
                if (SysParams.AllowGetStock)
                {
                    for (int i = 1; i <= SysParams.GatherMaxCount; i++)
                    {
                        ProgressBarControl runBarControl = new ProgressBarControl()
                        {
                            Name = "SubGatherStock" + i,
                            Visible = true
                        };

                        LayoutControlItem tmpItem = new LayoutControlItem(layProcessBar, runBarControl)
                        {
                            Text = string.Format("库存采集{0}", i),
                            TextVisible = true,
                            Visibility = LayoutVisibility.Always
                        };

                        _subProgressBarDic.Add(Guid.NewGuid().ToString(), runBarControl);
                    }
                }
                if (SysParams.AllowGetCoupon)
                {
                    for (int i = 1; i <= SysParams.GatherMaxCount; i++)
                    {
                        ProgressBarControl runBarControl = new ProgressBarControl()
                        {
                            Name = "SubGatherCoupon" + i,
                            Visible = true
                        };

                        LayoutControlItem tmpItem = new LayoutControlItem(layProcessBar, runBarControl)
                        {
                            Text = string.Format("优惠采集{0}", i),
                            TextVisible = true,
                            Visibility = LayoutVisibility.Always
                        };

                        _subProgressBarDic.Add(Guid.NewGuid().ToString(), runBarControl);
                    }
                }

            }
            else
            {
                SysParams.GatherMaxCount = 1;
                if (SysParams.AllowGetPrice)
                {
                    ProgressBarControl runBarControl1 = new ProgressBarControl()
                    {
                        Name = "SubGatherPrice",
                        Visible = true
                    };
                    LayoutControlItem tmpItem1 = new LayoutControlItem(layProcessBar, runBarControl1)
                    {
                        Text = "价格采集1",
                        TextVisible = true,
                        Visibility = LayoutVisibility.Always
                    };
                    _subProgressBarDic.Add(Guid.NewGuid().ToString(), runBarControl1);
                }
                if (SysParams.AllowGetStock)
                {
                    ProgressBarControl runBarControl1 = new ProgressBarControl()
                    {
                        Name = "SubGatherStock",
                        Visible = true
                    };
                    LayoutControlItem tmpItem1 = new LayoutControlItem(layProcessBar, runBarControl1)
                    {
                        Text = "库存采集2",
                        TextVisible = true,
                        Visibility = LayoutVisibility.Always
                    };
                    _subProgressBarDic.Add(Guid.NewGuid().ToString(), runBarControl1);
                }
                if (SysParams.AllowGetCoupon)
                {
                    ProgressBarControl runBarControl1 = new ProgressBarControl()
                    {
                        Name = "SubGatherCoupon",
                        Visible = true
                    };
                    LayoutControlItem tmpItem1 = new LayoutControlItem(layProcessBar, runBarControl1)
                    {
                        Text = "优惠采集3",
                        TextVisible = true,
                        Visibility = LayoutVisibility.Always
                    };
                    _subProgressBarDic.Add(Guid.NewGuid().ToString(), runBarControl1);
                }
            }

            ProgressBarControl runBarControl2 = new ProgressBarControl()
            {
                Name = "SubDBProcess",
                Visible = true
            };
            LayoutControlItem tmpItem2 = new LayoutControlItem(layProcessBar, runBarControl2)
            {
                Text = "入库线程",
                TextVisible = true,
                Visibility = LayoutVisibility.Always
            };
            _subProgressBarDic.Add(Guid.NewGuid().ToString(), runBarControl2);

            InitMainProcess(_subProgressBarDic.Count);
            txtMsg.Text = string.Format("本次采集任务共需采集{0}个商品" + "\r\n", _wares.Count);
        }

        Stopwatch _stopwathc = new Stopwatch();
        /// <summary>
        /// 线程启动状态
        /// </summary>
        private bool _isProcess = false;

        private void RunProcess()
        {
            if (_subProgressBarDic.Count <= 0) return;
            try
            {
                btnRun.Text = "采集中";
                btnRun.Enabled = false;
                _stopwathc.Restart();
                List<string> processList = _subProgressBarDic.Keys.Select(item => item.ToString()).ToList();

                JdListener.GetInstance().ProcessBarIDs = processList;
                JdListener.GetInstance().InitProcess = InitUpdateProcess;
                JdListener.GetInstance().ShowStep = ShowUpdateProcessing;
                JdListener.GetInstance().EndProcess = EndUpdateProcess;
                JdListener.GetInstance().ShowMessage = ShowGatherMessage;
                JdListener.GetInstance().UpdateWareThread(_wares);
            }
            catch (Exception ex)
            {
                Faster.XLogInfo(ex.Message);
            }

        }


        private void InitUpdateProcess(string processid, int leng)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<string, int>(InitUpdateProcess), processid, leng);
            }
            else
            {
                if (!string.IsNullOrEmpty(processid) && leng > 0 && _subProgressBarDic.ContainsKey(processid))
                {
                    ProgressBarControl runProcessBar = _subProgressBarDic[processid];
                    //设置一个最小值
                    runProcessBar.Properties.Minimum = 0;
                    //设置一个最大值
                    runProcessBar.Properties.Maximum = leng;
                    //设置步长，即每次增加的数
                    runProcessBar.Properties.Step = 1;
                    //显示数字
                    runProcessBar.Properties.ShowTitle = true;
                    //当前位置
                    runProcessBar.Position = 0;
                    //设置进度条的样式
                    runProcessBar.Properties.ProgressViewStyle = DevExpress.XtraEditors.Controls.ProgressViewStyle.Solid;
                }

                _isProcess = leng > 0;
            }
        }

        private void ShowUpdateProcessing(string processid, int iStep)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<string,int>(ShowUpdateProcessing), processid,iStep);
            }
            else
            {
                if (!string.IsNullOrEmpty(processid) && iStep > 0 && _subProgressBarDic.ContainsKey(processid))
                {
                    ProgressBarControl runProcessBar = _subProgressBarDic[processid];
                    runProcessBar.Text = iStep.ToString();
                    runProcessBar.EditValue = iStep;
                }
                
            }
        }

        private void EndUpdateProcess(string processid, bool bEnd)
        {
            _isProcess = !bEnd;
            if (bEnd)
            {
                _stopwathc.Stop();
                stepMain ++;
                MainProcessStep(stepMain);
            }
        }

        private void ShowGatherMessage(string msg)
        {
            if (txtMsg.InvokeRequired)
            {
                Action<string> ac = new Action<string>(ShowGatherMessage);
                txtMsg.Invoke(ac, msg);
            }
            else
            {
                txtMsg.Text = txtMsg.Text + (DateTime.Now.ToString() + " " + msg + "\r\n");
                txtMsg.SelectionStart = txtMsg.Text.Length;
                txtMsg.ScrollToCaret();
                //memoTypeMsg.Update();
            }
        }

        /// <summary>
        /// 主进度条
        /// </summary>
        /// <param name="leng"></param>
        private void InitMainProcess(int leng)
        {
            //设置一个最小值
            progressBarControl1.Properties.Minimum = 0;
            //设置一个最大值
            progressBarControl1.Properties.Maximum = leng;
            //设置步长，即每次增加的数
            progressBarControl1.Properties.Step = 1;
            //显示数字
            progressBarControl1.Properties.ShowTitle = true;
            //当前位置
            progressBarControl1.Position = 0;
            //设置进度条的样式
            progressBarControl1.Properties.ProgressViewStyle = DevExpress.XtraEditors.Controls.ProgressViewStyle.Solid;
        }

        private void MainProcessStep(int iStep)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<int>(MainProcessStep), iStep);
            }
            else
            {
                progressBarControl1.Text = iStep.ToString();
                progressBarControl1.EditValue = iStep;
                if (progressBarControl1.Properties.Maximum == (int)progressBarControl1.EditValue)
                {
                    btnRun.Text = "完成";
                    btnRun.Enabled = false;
                    _stopwathc.Stop();
                    txtMsg.Text += string.Format("本次操作于{0}结束，共计更新商品{1}个，耗时: {2}分钟（{3} ms）" + "\r\n", DateTime.Now, _wares.Count,
                    _stopwathc.ElapsedMilliseconds / 1000 / 60, _stopwathc.ElapsedMilliseconds);
                }
            }
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            RunProcess();
        }

        private void btnShowMsg_Click(object sender, EventArgs e)
        {
            layoutMain.BeginUpdate();
            txtMsg.Visible = false;
            layItemMemo.Visibility = LayoutVisibility.Never;
            layoutControlGroup3.Remove(layItemMemo);
            layoutMain.EndUpdate();
        }
    }
}
